package userShareModuleApi

import (
	"KumquatDrivesServices/common/res"
	"KumquatDrivesServices/enums"
	"KumquatDrivesServices/global"
	"KumquatDrivesServices/model"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

type checkShareCodeReq struct {
	ShareId   string `json:"shareId" binding:"required"`
	ShareCode string `json:"shareCode" binding:"required"`
}

func (UserShareModuleApi) CheckShareCode(c *gin.Context) {
	var req checkShareCodeReq
	if err := c.ShouldBindJSON(&req); err != nil {
		logrus.Errorf("CheckShareCode ShouldBindJSON err:%v", err)
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	var shareInfo model.ShareModel
	query := global.DB.Where("shareId=?", req.ShareId)
	if err := query.First(&shareInfo).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			res.FailWithCode(res.SHARE_NOT_EXIST_OR_EXPIRED, c)
			return
		}
		logrus.Errorf("CheckShareCode err:%v", err)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	if enums.IsExpired(shareInfo.ExpireTime) {
		res.FailWithCode(res.SHARE_NOT_EXIST_OR_EXPIRED, c)
		return
	}
	if req.ShareCode != shareInfo.SharePassWord {
		res.FailWithCode(res.TI_MA_CUO, c)
		return
	}
	info := authShareInfo{
		ShareId:         req.ShareId,
		ShareUserId:     shareInfo.UserID,
		ShareFileId:     shareInfo.FileID,
		ShareExpireTime: shareInfo.ExpireTime,
	}
	if err := setAuthShareCookie(req.ShareId, info, c); err != nil {
		logrus.Errorf("setAuthShareCookie err:%v", err)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	res.OkWithData(res.EmptyData, c)
}
